#!/bin/bash
tmp="/tmp/my.wget.http.tmp"
cookies="/tmp/my.wget.cookies"
wgetArgs="-q --load-cookies=$cookies --save-cookies=$cookies --keep-session-cookies -O $tmp"

#GET
doGet() {
	url="$1"
	test -e "$tmp" && rm -rf $tmp
	wget $wgetArgs "$url"
	test 0 -ne $? && return 1 || return 0
}

#POST
doPost() {
	data="$1"
	url="$2"
	test -e "$tmp" && rm -rf $tmp
	wget $wgetArgs --post-data="$data" "$url"
	test 0 -ne $? && return 1 || return 0
}

getResult() {
	cat "$tmp"
}


#从JSON数据中提出相应key的值(临时使用)
#getJSONValue() {
#   key="$1"
#   json="$2"
#	echo "$json" | awk -v key="$key" -F "[{},\[]" '{ for(i=1;i<=NF;i++) { if($i~key){ gsub(key"\":",""); gsub("\"","");gsub(" ","");print $i } } }'
#}

#从JSON中获取键的值
#有一个Bug如果[]中有嵌套的[]就会出错,{}类似
getJSONValue() {
	declare key="$1"
	declare json="$2"
	#取出键对应值的第一个字符
	declare startChar=$(expr match "$json" '.*'"$key"'["\s]*:[\s]*\(.\)')
	case "$startChar" in
		'[')
			expr match "$json" '.*'"$key"'["\s]*:[\s]*\([^]]*]\)'
			;;
		'{')
			expr match "$json" '.*'"$key"'["\s]*:[\s]*\([^}]*}\)'
			;;
		'"')
			expr match "$json" '.*'"$key"'["\s]*:[\s]*"\([^"]*\)"'
			;;
		*)
			expr match "$json" '.*'"$key"'["\s]*:[\s]*\([^,]*\)'
			;;
	esac
}
